<?php
namespace backend\models;


use common\models\db\User;
use yii\base\Model;

class FormResetPassword extends Model
{
    public $old_password;
    public $password;
    public $repassword;

    public function attributeLabels()
    {
        return [
            'old_password' => "旧密码",
            'password' => "新密码",
            'repassword' => "再次输入新密码",
        ];
    }

    public function rules()
    {
        return [
            ['old_password', 'trim'],
            ['old_password', 'required'],
            ['old_password', 'checkOldPassword'],
            ['password', 'trim'],
            ['password', 'required'],
            ['password', 'string', 'min' => 6],
            ['repassword', 'compare', 'compareAttribute' => 'password'],
        ];
    }

    public function checkOldPassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = \Yii::$app->user->identity;
            if (!$user->validatePassword($this->$attribute)) {
                $this->addError($attribute, '老密码验证错误');
            }
        }
    }

    public function doResetPassword()
    {
        $user = \Yii::$app->user->identity;
        $user->setPassword($this->password);
        if ($user->save()){
            \Yii::$app->session->addFlash('success', "重置密码成功!");
            return true;
        }else{
            \Yii::$app->session->addFlash('error', "重置密码失败!");
            return false;
        }
    }
}